import axios from 'axios'
import qs from 'qs'
import notification from 'ant-design-vue/es/notification'
import message from 'ant-design-vue/es/message'
import { VueAxios } from './axios'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  // baseURL: process.env.VUE_APP_API_BASE_URL,
  baseURL: '/',
  timeout: 6000 // 请求超时时间
})
request.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401) {
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  // application/x-www-form-urlencoded 参数处理
  if ((!config.headers['Content-Type'] || config.headers['Content-Type'].includes('application/x-www-form-urlencoded;charset=UTF-8'))) {
    config.data = qs.stringify(config.data)
  }
  return config
}, errorHandler)
// response interceptor
request.interceptors.response.use((response) => {
  if (response.data.msg) {
    message.error(response.data.msg)
    return Promise.reject(response.data)
  } else {
    return response.data
  }
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}
export default request

export {
  installer as VueAxios,
  request as axios
}
